<template>
  <div class="checkout-address">
    <div class="text">
      <div class="none" v-if="!showAddress">请先添加收货地址。</div>
      <ul v-if="showAddress">
        <li>
          <span>收<i />货<i />人：</span>{{ showAddress.receiver }}
        </li>
        <li>
          <span>联系方式：</span>
          {{ showAddress.contact.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') }}
        </li>
        <li>
          <span>收货地址：</span>
          {{ showAddress.fullLocation + showAddress.address }}
        </li>
      </ul>
      <a
        @click="openAddressEdit(showAddress)"
        href="javascript:;"
        v-if="showAddress"
        >修改地址</a
      >
    </div>
    <div class="action">
      <xtx-button class="btn" @click="openDialog()">切换地址</xtx-button>
      <xtx-button class="btn" @click="openAddressEdit({})">添加地址</xtx-button>
    </div>
  </div>
  <!-- 对话框组件-切换收货地址 -->
  <xtx-dialog class="dialog" title="切换收货地址" v-model="dialogVisable">
    <div
      class="addressList item"
      v-for="item in addressList"
      :key="item.id"
      :class="{ active: selectedAddress && selectedAddress.id === item.id }"
      @click="selectedAddress = item"
    >
      <ul>
        <li>
          <span>收<i />货<i />人：</span>
          {{ item.receiver }}
        </li>
        <li>
          <span>联系方式：</span>
          {{ item.contact.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') }}
        </li>
        <li>
          <span>收货地址：</span>
          {{ item.fullLocation + item.address }}
        </li>
      </ul>
    </div>
    <template #footer>
      <XtxButton @click="cancle()" type="gray" style="margin-right: 20px"
        >取消</XtxButton
      >
      <XtxButton @click="confirmAddressFn()" type="primary">确认</XtxButton>
    </template>
  </xtx-dialog>
  <!-- 收货地址添加编辑组件 -->
  <addressEdit ref="addressEditCom" @on-success="successHandler"></addressEdit>
</template>
<script>
import { ref } from 'vue'
import addressEdit from './address-edit.vue'
import { message } from '@/components/library/message'
import { stop, move } from '@/utils/dialog'
// import { findAddressList } from '@/api/order'
export default {
  name: 'CheckoutAdress',
  components: { addressEdit },
  // 由于当前组件不止一个根元素，所以需要指定emits，避免控制台会警告
  emits: ['change'],
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    // 显示地址
    const showAddress = ref(null)
    const defaultAddress = props.list.find((item) => item.isDefault === 0)
    if (defaultAddress) {
      showAddress.value = defaultAddress
    } else {
      if (props.list.length) {
        // 加上一个注释：忽略下面代码的检查eslint
        // eslint-disable-next-line vue/no-setup-props-destructure
        showAddress.value = props.list[0]
      }
    }
    // 默认通知父组件一个收货地址ID
    emit('change', showAddress.value && showAddress.value.id)

    /**
     * 切换地址对话框显示隐藏
     * @return {}
     */
    const dialogVisable = ref(false)
    // 选择的地址（临时的）
    const selectedAddress = ref(null)
    // 打开对话框
    const openDialog = () => {
      // 默认选中显示的地址
      // selectedAddress.value = showAddress.value
      // 将之前的选中地址改成null
      if (props.list.length === 0) {
        message({
          message: '您还没有有效的收货地址,请先添加',
          type: 'warn'
        })
      } else {
        dialogVisable.value = true
        // 禁止滚动-在显示遮罩层的时候调用
        stop()
      }
      selectedAddress.value = null
    }
    // 取消
    const cancle = () => {
      dialogVisable.value = false
      // 取消滑动限制-在关闭遮罩层的时候调用
      move()
    }
    // 确认地址
    const confirmAddressFn = () => {
      // 更新显示地址
      showAddress.value = selectedAddress.value
      dialogVisable.value = false
      // 取消滑动限制-在关闭遮罩层的时候调用
      move()
    }

    /**
     * 添加收货地址组件
     * @return {}
     */
    const addressEditCom = ref(null)
    const openAddressEdit = (address) => {
      // 添加 {}  修改 {数据}
      addressEditCom.value.open(address)
    }

    // 获取收货地址列表
    // 注意：props 数据不能直接修改，所以需要声明一个新的变量，初始值为 props.list
    const addressList = ref(props.list)
    // 获取最新收货地址列表 - 地址添加或修改的时候触发这个函数
    const successHandler = (form) => {
      // 根据formData中的ID去当前地址列表中查找，有就是修改，否则是添加
      const address = props.list.find((item) => item.id === form.id)
      if (address) {
        for (const key in address) {
          address[key] = form[key]
        }
      } else {
        // 如果是添加：往list中追加一条
        // 当你在修改formData的时候，数组中的数据也会更新，因为是同一引用地址。
        // 啥时候修改formData，当你打开对话框需要清空之前的输入信息
        // 克隆formData数据
        const jsonStr = JSON.stringify(form)
        // eslint-disable-next-line vue/no-mutating-props
        addressList.value.unshift(JSON.parse(jsonStr))
      }
    }
    return {
      showAddress,
      selectedAddress,
      dialogVisable,
      openDialog,
      confirmAddressFn,
      addressEditCom,
      openAddressEdit,
      addressList,
      successHandler,
      cancle,
      stop,
      move
    }
  }
}
</script>
<style scoped lang="less">
.dialog {
  .addressList {
    flex: 1;
    min-height: 90px;
    display: flex;
    align-items: center;
    &.item {
      border: 1px solid #f5f5f5;
      margin-bottom: 10px;
      cursor: pointer;
      &.active,
      &:hover {
        border-color: @color;
        background: lighten(@color, 50%);
      }
      > ul {
        padding: 10px;
        font-size: 14px;
        line-height: 30px;
        li {
          span {
            > i {
              display: inline-block !important;
              width: 0.5em !important;
            }
          }
        }
      }
    }
  }
}
.checkout-address {
  display: flex;
  border: 1px solid #eee;
  // padding: 10px 0;
  .text {
    width: 80%;
    min-height: 90px;
    display: flex;
    align-items: center;
    // justify-content: space-between;
    .none {
      line-height: 90px;
      color: #999;
      text-align: center;
      width: 100%;
    }
    ul {
      flex: 1;
      padding: 20px;
      li {
        &:first-child {
          letter-spacing: 1px;
        }
        line-height: 30px;
        span {
          color: #999;
          margin-right: 5px;
          > i {
            width: 0.5em;
            display: inline-block;
          }
        }
      }
    }

    a {
      color: @color;
      width: 160px;
      text-align: center;
      height: 90px;
      line-height: 90px;
      border-right: 1px solid #eee;
    }
  }
  .action {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 0 65px;

    .btn {
      width: 140px;
      height: 46px;
      line-height: 44px;
      font-size: 14px;
      border-radius: 4px;
      &:first-child {
        margin-right: 10px;
      }
    }
  }
}
</style>
